﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Collections;

namespace WindowsFormsApplication1
{
	public class Utils
	{
		public static string FormatBytes(long size)
		{
			long groupSize = 1024;
			double div = 0;
			int step = 0;
			string um = "";

			while (true)
			{
				div = size / Math.Pow(groupSize, step);
				if (div > groupSize) step++;
				else break;
			}

			switch (step)
			{
				case 0:
					um = "B";
					break;
				case 1:
					um = "KB";
					break;
				case 2:
					um = "MB";
					break;
				case 3:
					um = "GB";
					break;
				case 4:
					um = "TB";
					break;
			}

			return string.Format("{0:###,###,##0.00} {1}", div, um);
		}

		public static void LoadJobs(DataSetBackup.ProgressDataTable table)
		{
			if (System.IO.File.Exists("settings.xml"))
			{
				XElement settings = XElement.Load("settings.xml");
				var query = from el in settings.Elements()
							where el.Name == "job"
							select el;
				foreach (XElement el in query)
				{
					DataSetBackup.ProgressRow row = table.NewProgressRow();
					row.jobname = el.Element("jobname").Value;
					row.origin = el.Element("origin").Value;
					row.destination = el.Element("destination").Value;
                    row.copyonlynewfiles = Convert.ToBoolean(el.Element("copyonlynewfiles").Value);
					table.AddProgressRow(row);
				}
			}
		}

		public static void SaveJobs(DataSetBackup.ProgressDataTable table)
		{
			XElement settings = new XElement("settings");
			XDocument doc = new XDocument(settings);
			
			foreach (DataSetBackup.ProgressRow row in table)
			{
				XElement job = new XElement("job",
					new XElement("jobname", row.jobname),
					new XElement("origin", row.origin),
					new XElement("destination", row.destination),
                    new XElement("copyonlynewfiles", row.copyonlynewfiles)
					);
				settings.Add(job);
			}

			doc.Save("settings.xml");
		}
	}
}
